<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">媒体统计</span>
          <span class='ml-2 mr-2'>
            <el-date-picker
                    style='width: 100%'
                    v-model="value1"
                    type="daterange"
                    range-separator="——"
                    start-placeholder="开始"
                    end-placeholder="结束"
                    size='small'
                    @change='handleTime'
            />
        </span>
        <div  style='white-space:nowrap;'>
          <el-check-tag
            v-for="(item, index) in options"
            :key="index"
            :checked="current == item.value"
            style="margin-right: 8px"
            @click="handleChoose(item.value)"
            >{{ item.text }}</el-check-tag
          >
        </div>
      </div>
    </template>
    <div ref="el" id="chart" style="width: 100%; height: 300px"></div>
  </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue"
import * as echarts from "echarts"
import { useResizeObserver } from "@vueuse/core"

// import { getHome2 } from "~/api/index.js"

// 日期范围选择器
const value1 = ref('')
const handleTime = (e) => {
    const currentDate = new Date();
    const startValue = value1.value[0]
    const endValue = value1.value[1];
    // 结束时间不能超过当天
    if (startValue && startValue > currentDate) {
        value1.value[0] = currentDate;
    }

    // 结束时间不能超过当天
    if (endValue && endValue > currentDate) {
        value1.value[1] = currentDate;
    }
}

const current = ref("week");
const options = [
  {
    text: "近1周",
    value: "week",
  },
  {
    text: "近1月",
    value: "month",
  },
  {
    text: "近3月",
    value: "other",
  },
];

const handleChoose = (type) => {
  current.value = type;
  getData();
};

var myChart = null;
onMounted(() => {
  var chartDom = document.getElementById("chart");
  if (chartDom) {
    myChart = echarts.init(chartDom);
    getData();
  }
});

onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart);
});

function getData() {
  let option = {
    xAxis: {
      type: "category",
      data: ['2024-05-18','2024-05-19','2024-05-20','2024-05-21','2024-05-22','2024-05-23','2024-05-24'],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [10,20,30,41,80,60,40],
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
      },
    ],
  };

  myChart.setOption(option)
  
  // 加载数据
  // myChart.showLoading();
  // getHome2(current.value)
  //   .then((res) => {
  //     option.xAxis.data = res.data.x;
  //     option.series[0].data = res.data.y;

  //     myChart.setOption(option);
  //   })
  //   .finally(() => {
  //     myChart.hideLoading();
  //   });
}

const el = ref(null);
useResizeObserver(el, (entries) => myChart.resize());
</script>
